package com.kjc.demo.netty.client;


import org.springframework.stereotype.Component;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author kangjichang
 * @date 2022/7/28
 **/
@Component
@Slf4j
public class NettyClientChannelInitializer extends ChannelInitializer {
	
	private final NioNettyClient nioNettyClient;

    public NettyClientChannelInitializer(NioNettyClient nioNettyClient) {
            this.nioNettyClient = nioNettyClient;
        }


    @Override
    protected void initChannel(Channel channel) {
        channel.pipeline().addLast("decoder",new StringDecoder(CharsetUtil.UTF_8));
        channel.pipeline().addLast("encoder",new StringEncoder(CharsetUtil.UTF_8));
        channel.pipeline().addLast("responseChannelHandler",new ResponseChannelHandler(nioNettyClient));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("error message {}",cause.getMessage(),cause);
        super.exceptionCaught(ctx, cause);
    }
}
